   //@ts-check
   import fp from 'lodash/fp.js'
//    setTimeout(function(){
//         var a = 'hello '
//         setTimeout(function(){
//             var b = 'lagou '
//             setTimeout(function(){
//                 var c = 'I Love U'
//                 console.log(a+b+c)
//             },10)
//         },10)
//     },10)
    //使用Promise 改造

    
function task1(msg){
    return new Promise(resolve=> {
        setTimeout(function(){
            resolve(msg)
        },10)
    })
}

// task1('hello ').then(msg => msg+'lagou ').then(msg => console.log(msg+'I Love U'))



const cars = [
    {name: 'Ferrari FF',horsepower:660,dollar_value:700000,in_stock:true},
    {name: 'Spyker C12 Zagato',horsepower:650,dollar_value:648000,in_stock:false},
    {name: 'Jaguar XKR-S',horsepower:550,dollar_value:132000,in_stock:false},
    {name: 'Aston Martin One-77',horsepower:750,dollar_value:1850000,in_stock:true},
    {name: 'Pagani Huayra',horsepower:700,dollar_value:1300000,in_stock:false},
]

let isLastInStock = function(cars){
    //获取最后一条数据
    let last_car = fp.last(cars)
    //获取最后一条数据的in_stock
    return fp.prop('in_stock',last_car)
}

console.log(isLastInStock(cars))
//练习1 获取最后一个cars的in_stock
let task2 = fp.flowRight(fp.prop('in_stock'), fp.last)
console.log(task2(cars))
//练习2 获取第一个car的name
let task3 = fp.flowRight(fp.prop('name'),fp.first)
console.log(task3(cars))

//练习3 使用帮助函数_average重构averageDollarValue，使用函数组合的方式实现

let _average = function(xs){
    return fp.reduce(fp.add, 0, xs)
} // 无须改动
let averageDollarValue = function (cars){
    let dollar_value = fp.map(function(car){
        return car.dollar_value
    },cars)

    return _average(dollar_value)
}
console.log(averageDollarValue(cars))

let task4 = fp.flowRight(_average, fp.map(fp.prop('dollar_value')))
console.log(task4(cars))

//练习4: 使用flowRight写一个sanitizeNames()函数，返回一个下划线连接的小写字符串，把数组中的name转换为这种形式： 例如：
//sanitizeNames(["Hello World"]) => ["hello_world"]

let _underscore = fp.replace(/\W+/g, '_')

let sanitizeNames = fp.map(car => {
    car.name = fp.flowRight(_underscore,fp.toLower)(car.name)
    return car
})
console.log(sanitizeNames(cars))

//三 基于下面提供的代码，完成后续的四个练习

//练习1: 使用fp.add(x,y) 和 fp.map(f,x) 创建一个能让functor里的值增加的函数ex1

import {Maybe,Container} from './support.js'

let maybe = Maybe.of([5,6,1])

let ex1 = maybe.map(x => fp.map(fp.add(1),x))
console.log(ex1)

//练习2：实现一个函数 ex2，能够使用 fp.first 获取列表的第一个元素
let xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'ti', 'do'])
let ex2 = xs.map(fp.first)
console.log(ex2)
//练习3：实现一个函数 ex3，使用 safeProp 和 fp.first 找到 user 的名字的首字母
let safeProp = fp.curry(function (x, o) { return Maybe.of(o[x]) })
let user = { id: 2, name: "Albert" }
let ex3 = fp.flowRight(fp.map(fp.first),safeProp('name'))
console.log(ex3(user))
//练习4：使用 Maybe 重写 ex4，不要有 if 语句
let ex4 = function(n){
    if(n) {
        return parseInt(n)
    }
}
let re_ex4 = n=> Maybe.of(n).map(parseInt)
console.log(re_ex4('Abc'))


